package tech.brick.easysharer.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tech.brick.easysharer.model.HeartbeatResponse;
import tech.brick.easysharer.model.ServiceRegistry;
import tech.brick.easysharer.model.ServiceRegistryResponse;
import tech.brick.easysharer.util.NetworkUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class ServiceRegistryService {

    private final RestTemplate restTemplate;

    @Value("${server.port:9090}")
    private Integer serverPort;

    @Value("${service.registry.url:https://api.banzhuan.tech/api}")
    private String registryUrl;

    @Value("${service.registry.service-type:fileshare}")
    private String serviceType;

    @Value("${service.registry.description:EasySharer}")
    private String description;

    @Value("${service.registry.version:1.0.0}")
    private String version;

    private Integer serviceId;

    /**
     * 注册服务到远程注册中心
     */
    public boolean registerService() {
        try {
            String lanIp = NetworkUtils.getLocalIpAddress();
            
            ServiceRegistry registry = new ServiceRegistry();
            registry.setLanIp(lanIp);
            registry.setPort(serverPort);
            registry.setHealthPath("/health");
            registry.setServiceType(serviceType);
            registry.setDescription(description);
            registry.setVersion(version);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<ServiceRegistry> request = new HttpEntity<>(registry, headers);

            String registerUrl = registryUrl + "/service/register";
            log.info("正在注册服务到: {}", registerUrl);
            log.info("注册信息: {}", registry);

            ResponseEntity<ServiceRegistryResponse> response = restTemplate.postForEntity(
                registerUrl, request, ServiceRegistryResponse.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                ServiceRegistryResponse body = response.getBody();
                if (body.getCode() == 0 && body.getData() != null) {
                    this.serviceId = body.getData().getServiceId();
                    log.info("服务注册成功，服务ID: {}", this.serviceId);
                    return true;
                } else {
                    log.error("服务注册失败: {}", body.getMessage());
                }
            } else {
                log.error("服务注册请求失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("服务注册异常", e);
        }
        return false;
    }

    /**
     * 发送心跳更新
     */
    public boolean sendHeartbeat() {
        if (serviceId == null) {
            log.warn("服务ID为空，无法发送心跳");
            return false;
        }

        try {
            String heartbeatUrl = registryUrl + "/service/heartbeat/" + serviceId;
            log.debug("发送心跳到: {}", heartbeatUrl);

            ResponseEntity<HeartbeatResponse> response = restTemplate.postForEntity(
                heartbeatUrl, null, HeartbeatResponse.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                HeartbeatResponse body = response.getBody();
                if (body.getCode() == 0) {
                    log.debug("心跳发送成功");
                    return true;
                } else {
                    log.error("心跳发送失败: {}", body.getMessage());
                }
            } else {
                log.error("心跳请求失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("心跳发送异常", e);
        }
        return false;
    }

    /**
     * 获取服务ID
     */
    public Integer getServiceId() {
        return serviceId;
    }
}
